#!/bin/sh

usage(){
	echo "General information about process $0 -c/-p|<process name>/<pid>"
}

if (( $# != 2 ))
then
	echo "Needs 2 parameters"
	usage
	exit 0
elif [[ "$1" -ne "-c" ]] || [[ "$1" -ne "-p" ]];
then
	echo "Wrong parameters"
	usage
	exit 0
fi


#all_proc_fname=""
#all_proc_pid=""
#all_proc_ppid=""
main_fname=""
main_pid=""
main_ppid=""
father_pid=""
father_fname=""

all=`ps -eo pid,comm,ppid | grep -v PID`
all_proc=($all)
n_all_proc=${#all_proc[*]}
j=(n_all_proc/3)

k=0 #PID
m=0 #FNAME
n=0 #PPID
t=0

for ((i=0; $i<$j; ((i=i+3))));
do
	k=$i
	((m=$i+1))
	((n=$i+2))
	all_proc_pid[$t]=${all_proc[$k]}
	all_proc_fname[$t]=${all_proc[$m]}
	all_proc_ppid[$t]=${all_proc[$n]}
	((t=t+1))
done

n_all_proc_pid=${#all_proc_pid[*]}
n_all_proc_fname=${#all_proc_fname[*]}
n_all_proc_ppid=${#all_proc_ppid[*]}

if [[ "$1" == "-c" ]]; 
then
	main_fname=$2
	for ((i=0; $i<$n_all_proc_fname; i++));
	do
		if [[ "${all_proc_fname[$i]}" == "$main_fname" ]];
		then
			main_pid=${all_proc_pid[$i]}
			main_ppid=${all_proc_ppid[$i]}
			father_pid=$main_ppid

		fi
	done
elif [[ "$1" == "-p" ]]; 
then
	main_pid=$2
	for ((i=0; $i<$n_all_proc_pid; i++));
	do
		if [[ "${all_proc_pid[$i]}" -eq "$main_pid" ]];
		then
			main_fname=${all_proc_fname[$i]}
			main_ppid=${all_proc_ppid[$i]}
			father_pid=$main_ppid
		fi
	done
fi

#Finds out father_fname

for ((i=0; $i<$n_all_proc_pid; i++));
do
	if [[ "${all_proc_pid[$i]}" -eq "$father_pid" ]];
	then
		father_fname=${all_proc_fname[$i]}
	fi
done


#echo "main_pid=$main_pid"
#echo "main_fname=$main_fname"
#echo "main_ppid=$main_ppid"
#echo "${all_proc_pid[0]}"
##echo "${all_proc_fname[0]}"
#echo "${all_proc_ppid[0]}"

echo "#############"
echo "#####$father_pid####"
echo "#####$father_fname####"
echo "                    |"
echo "                    |"
echo "                    ###################"
echo "                    ########$main_pid###########"
echo "                    ########$main_fname###########"
echo "							|"
echo "							|"

for ((i=0; $i<$n_all_proc; i++));
do
#echo "${all_proc_pid[$i]} - ${all_proc_fname[$i]}"
	echo "${all_proc_pid[$i]}" 
done


#for ((i=0; $i<$n_all_proc; i++));
#do
#	if [[ "${all_proc_pid[$i]}" -eq "$main_pid" ]];
#	then
#		echo "${all_proc_pid[$i]} - ${all_proc_fname[$i]}"
#	fi
#done
exit 0

